package com.weedsdream.app.compose

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.weedsdream.app.R
import com.weedsdream.app.colorplate.curRGB
import com.weedsdream.app.compose.OriType.上
import com.weedsdream.app.compose.OriType.下
import com.weedsdream.app.compose.OriType.右
import com.weedsdream.app.compose.OriType.左
import com.weedsdream.app.struct.Path
import com.weedsdream.app.struct.drafts
import com.weedsdream.function.inCoroutine
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay

/**被选中的路径<颜色,路径>*/
var chosenPaths = mutableStateMapOf<Color, SnapshotStateList<Path>>()

/**多选模式*/
var mulChoice by mutableStateOf(false)

/**按钮组*/
@Composable
fun RowScope.ChosenPathBtn(test: Boolean = true) {
    if (test || chosenPaths.isNotEmpty()) Row(Modifier.align(Alignment.CenterVertically)) {
        val mod = { click: () -> Unit ->
            Modifier
                .clickable { click() }
                .padding(10.dp)
        }
        if (chosenPaths.size > 1 || chosenPaths.size == 1 && curRGB != chosenPaths.keys.first()) Text(
            text = "变色", fontSize = 15.sp, color = curRGB, modifier = mod {
                val map = chosenPaths.toMap()
                chosenPaths.clear()
                if (drafts[curRGB] == null) drafts[curRGB] = mutableStateListOf()
                chosenPaths[curRGB] = mutableStateListOf()
                for ((color, paths) in map) {
                    for (path in paths) {
                        drafts[color]!!.remove(path)
                        drafts[curRGB]!!.add(path)
                        chosenPaths[curRGB]!!.add(path)
                    }
                }
            })
        Text(text = "移动", fontSize = 15.sp, color = if (dragPos) Color.Cyan else Color.Black,
            modifier = mod { dragPos = !dragPos })
        Text(text = "删除", fontSize = 15.sp, color = Color.Red, modifier = mod {
            for ((color, paths) in chosenPaths) drafts[color]!!.removeAll(paths)
            chosenPaths.clear()
            dragPos = false
        })
        if (!dragPos) Spacer(
            Modifier
                .padding(horizontal = 10.dp)
                .height(25.dp)
                .width(1.dp)
                .background(Color.Black)
                .align(Alignment.CenterVertically)
        )
    }
    if (!dragPos) Row(
        Modifier
            .padding(horizontal = 10.dp)
            .align(Alignment.CenterVertically)
            .pointerInput(Unit) {
                detectTapGestures { mulChoice = !mulChoice }
            }) {
        Text(
            text = "多选", fontSize = 15.sp, color = if (mulChoice) Color.Cyan else Color.Black,
            modifier = Modifier.align(Alignment.CenterVertically)
        )
        Icon(
            painterResource(
                id = if (mulChoice) R.drawable.select_yes else R.drawable.select_no
            ), null, Modifier
                .padding(start = 5.dp)
                .size(25.dp)
                .align(Alignment.CenterVertically),
            Color.Unspecified
        )
    }
}

@Preview
@Composable
private fun Test() {
    Row {
        ChosenPathBtn()
    }
}

/**选中时的微调按钮内容*/
@Preview(widthDp = 600, heightDp = 350)
@Composable
fun ChosenPathContent(test: Boolean = true) {
    Box(Modifier.fillMaxSize()) {
        if (test || dragPos) Row(Modifier.align(Alignment.BottomEnd)) {
            Text(
                "滑动屏幕移动选中线条\n或使用右侧按钮微调>>", fontSize = 13.sp,
                modifier = Modifier.align(Alignment.Bottom)
            )
            Btn()
        }
    }
}

/**微调按钮组*/
@Composable
private fun Btn() {
    Box(
        Modifier
            .padding(10.dp)
            .size(150.dp, 110.dp)
    ) {
        val icon = @Composable { rotate: Float, ori: OriType ->
            Icon(
                Icons.AutoMirrored.Filled.ArrowBack, null,
                Modifier
                    .size(40.dp)
                    .rotate(rotate)
                    .pointerInput(Unit) {
                        detectTapGestures(onPress = {
                            dragOri = ori
                            inCoroutine(Dispatchers.Default) {
                                while (dragOri == ori) {
                                    for (paths in chosenPaths.values) for (path in paths) when (ori) {
                                        上 -> path.movePath(0f, -DIS)

                                        下 -> path.movePath(0f, DIS)

                                        左 -> path.movePath(-DIS, 0f)

                                        右 -> path.movePath(DIS, 0f)
                                    }
                                    delay(60)
                                }
                            }
                            tryAwaitRelease() // 抬起或取消(超出范围)
                            dragOri = null
                        })
                    }, if (dragOri == ori) Color.Cyan else Color.Unspecified
            )
        }
        Row {
            Box(Modifier.align(Alignment.CenterVertically)) { icon(0f, 左) }
            Spacer(Modifier.weight(1f))
            Column {
                icon(90f, 上)
                Spacer(Modifier.weight(1f))
                icon(270f, 下)
            }
            Spacer(Modifier.weight(1f))
            Box(Modifier.align(Alignment.CenterVertically)) { icon(180f, 右) }
        }
    }
}

/**当前是否处于拖动位置状态下*/
var dragPos by mutableStateOf(false)

/**当拖动状态下时，当前的微调按压方向*/
private var dragOri by mutableStateOf<OriType?>(null)

/**拖动状态下按手指按下的初始距离*/
var chosePath2pressPos = Offset.Zero

/**方向类型*/
@Suppress("EnumEntryName", "NonAsciiCharacters")
private enum class OriType {
    上, 下, 左, 右
}

/**微调修改的距离*/
private const val DIS = 1f

/**整体移动路径
 * @param x 水平方向移动距离
 * @param y 垂直方向移动距离*/
fun Path.movePath(x: Float, y: Float) {
    for (i in points.indices) {
        val p = points[i]
        points[i] = Offset(p.x + x, p.y + y)
    }
}